﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace ConsoleApp8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
            LoadUserDirectories();
        }
        

        private void LoadUserDirectories()
        {
            treeView.Nodes.Clear();

            // 获取用户目录
            string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            TreeNode rootNode = new TreeNode("用户目录", 0, 0);
            rootNode.Tag = userProfile;
            treeView.Nodes.Add(rootNode);

            // 加载一级子目录
            LoadSubDirectories(rootNode);
        }
        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void RefreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadUserDirectories();
        }

        private void RefreshToolStripButton_Click(object sender, EventArgs e)
        {
            LoadUserDirectories();
        }
        private void LoadSubDirectories(TreeNode parentNode)
        {
            string path = parentNode.Tag as string;

            try
            {
                foreach (string directory in Directory.GetDirectories(path))
                {
                    TreeNode node = new TreeNode(Path.GetFileName(directory), 0, 0);
                    node.Tag = directory;
                    parentNode.Nodes.Add(node);

                    // 预加载一级子目录以便显示展开图标
                    try
                    {
                        if (Directory.GetDirectories(directory).Length > 0)
                        {
                            node.Nodes.Add(new TreeNode("temp")); // 占位节点
                        }
                    }
                    catch { }
                }
            }
            catch (UnauthorizedAccessException)
            {
                parentNode.ImageIndex = 1;
                parentNode.SelectedImageIndex = 1;
            }
        }

        private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            listView.Items.Clear();

            string path = e.Node.Tag as string;
            if (string.IsNullOrEmpty(path)) return;

            try
            {
                // 添加子目录
                foreach (string directory in Directory.GetDirectories(path))
                {
                    DirectoryInfo dirInfo = new DirectoryInfo(directory);
                    ListViewItem item = new ListViewItem(dirInfo.Name);
                    item.SubItems.Add("文件夹");
                    item.SubItems.Add(dirInfo.LastWriteTime.ToString());
                    item.SubItems.Add("");
                    item.Tag = directory;
                    listView.Items.Add(item);
                }

                // 添加文件
                foreach (string file in Directory.GetFiles(path))
                {
                    FileInfo fileInfo = new FileInfo(file);
                    ListViewItem item = new ListViewItem(fileInfo.Name);
                    item.SubItems.Add(fileInfo.Extension);
                    item.SubItems.Add(fileInfo.LastWriteTime.ToString());
                    item.SubItems.Add(fileInfo.Length.ToString());
                    item.Tag = file;
                    listView.Items.Add(item);
                }
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show($"无法访问: {path}", "权限不足", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void ListView_DoubleClick(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count == 0) return;

            string path = listView.SelectedItems[0].Tag as string;
            if (string.IsNullOrEmpty(path)) return;

            if (Directory.Exists(path))
            {
                // 如果是目录，展开树形视图
                foreach (TreeNode node in treeView.Nodes)
                {
                    ExpandAndSelectNode(node, path);
                }
            }
            else if (File.Exists(path) && Path.GetExtension(path).ToLower() == ".xml")
            {
                // 如果是XML文件，显示内容
                ShowXmlContent(path);
            }
        }

        private bool ExpandAndSelectNode(TreeNode node, string path)
        {
            if (node.Tag as string == path)
            {
                node.Expand();
                treeView.SelectedNode = node;
                return true;
            }

            foreach (TreeNode child in node.Nodes)
            {
                if (ExpandAndSelectNode(child, path))
                {
                    node.Expand();
                    return true;
                }
            }

            return false;
        }

        private void ShowXmlContent(string xmlFilePath)
        {
            try
            {
                Form xmlViewer = new Form();
                xmlViewer.Text = $"XML 查看器 - {Path.GetFileName(xmlFilePath)}";
                xmlViewer.Size = new System.Drawing.Size(600, 400);

                TreeView xmlTree = new TreeView();
                xmlTree.Dock = DockStyle.Fill;
                xmlViewer.Controls.Add(xmlTree);

                XmlDocument doc = new XmlDocument();
                doc.Load(xmlFilePath);

                AddXmlNodeToTree(doc.DocumentElement, xmlTree.Nodes);

                xmlViewer.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法解析XML文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AddXmlNodeToTree(XmlNode xmlNode, TreeNodeCollection treeNodes)
        {
            TreeNode node = new TreeNode(xmlNode.Name);

            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attr in xmlNode.Attributes)
                {
                    TreeNode attrNode = new TreeNode($"@{attr.Name} = {attr.Value}");
                    node.Nodes.Add(attrNode);
                }
            }

            if (!string.IsNullOrEmpty(xmlNode.InnerText) && xmlNode.ChildNodes.Count == 0)
            {
                node.Text += $" = {xmlNode.InnerText}";
            }

            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                AddXmlNodeToTree(childNode, node.Nodes);
            }

            treeNodes.Add(node);
        }
    }

}
